//npm instal chokidar --save-dev
const path = require("path");
const chokidar = require("chokidar");

// 监听单个文件
const fileWatcher = chokidar.watch("example.txt", {
  persistent: true,
  ignoreInitial: true,
});

// 监听事件
fileWatcher
  .on("add", (path) => console.log(`文件 ${path} 被添加`))
  .on("change", (path) => {
    console.log(`文件 ${path} 被修改`);
    // 处理文件变化
  })
  .on("unlink", (path) => console.log(`文件 ${path} 被删除`))
  .on("error", (error) => console.error("错误:", error));

// 监听整个目录
const dirWatcher = chokidar.watch("./src", {
  persistent: true,
  ignoreInitial: true,
  ignored: /(^|[\/\\])\../, // 忽略隐藏文件
});

dirWatcher.on("all", (event, path) => {
  console.log(`目录事件 ${event} 发生在 ${path}`);
});

// 停止监听
// setTimeout(() => {
//   fileWatcher.close();
//   dirWatcher.close();
// }, 30000);
